<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="openItemDialog(false)">添加团队</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column label="团队名称" prop="name" min-width="180" align="center"></el-table-column>
        <el-table-column label="组长" prop="managerName" min-width="180" align="center"></el-table-column>
        <el-table-column label="组员" prop="membersName" min-width="180" align="center"></el-table-column>
        <el-table-column label="国家" prop="countryNames" min-width="180" align="center"></el-table-column>
        <el-table-column label="操作" min-width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="openItemDialog(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="removeItem(scope.row.id)" type="text" size="small">删除</el-button>
            <el-button @click="openSaleDialog(scope.row)" type="text" size="small">分解业绩目标</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="团队管理" :visible.sync="itemDialog" width="600px" :close-on-click-modal="false"> 
      <el-form :model="form" style="padding-right:100px;padding-left: 50px;" label-width="120px">
        <el-form-item label="团队名称：">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="组长：">
          <el-tooltip class="item" effect="dark" :disabled="form.managerName.length === 0" :content="form.managerName" placement="bottom">
            <el-input placeholder="请选择" style="width: 210px;" v-model="form.managerName" :disabled="true"></el-input>
          </el-tooltip>
          <el-button @click="selectDingUsers('managerIdArr','managerName','managerId', 1)">选择</el-button>
        </el-form-item>
        <el-form-item label="组员：">
          <el-tooltip class="item" effect="dark" :disabled="form.membersName.length === 0" :content="form.membersName" placement="bottom">
            <el-input placeholder="请选择" style="width: 210px;" v-model="form.membersName" :disabled="true"></el-input>
          </el-tooltip>
          <el-button @click="selectDingUsers('membersIdArr','membersName','membersId', 300)">选择</el-button>
        </el-form-item>
        <el-form-item label="国家：">
          <el-select ref="labelSelected" style="width: 100%;" :multiple="true" :filterable="true" v-model="countryCodeStr" placeholder="请选择国家">
            <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.nameCode"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="itemDialog = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="业绩目标" :visible.sync="saleDialog" width="1200px" :close-on-click-modal="false"> 
      <el-form :inline="true">
        <el-form-item>
          <el-date-picker type="year" @change="changeYear" value-format="yyyy" placeholder="选择日期" v-model="saleDate" style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <div style="max-height: 500px;overflow-y:auto;">
        <el-table :data="saleData" border style="width: 100%" :summary-method="getSummaries" show-summary>
          <el-table-column label="国家" prop="name" min-width="100" align="center"></el-table-column>
          <el-table-column label="所属团队" prop="teamName" min-width="100" align="center"></el-table-column>
          <el-table-column label="第一季度目标" prop="quarter1" min-width="100" align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{scope.row.quarter1}}</span>
              <el-input v-if="scope.row.isEdit" v-model="scope.row.quarter1"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第二季度目标" prop="quarter2" min-width="100" align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{scope.row.quarter2}}</span>
              <el-input v-if="scope.row.isEdit" v-model="scope.row.quarter2"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第三季度目标" prop="quarter3" min-width="100" align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{scope.row.quarter3}}</span>
              <el-input v-if="scope.row.isEdit" v-model="scope.row.quarter3"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第四季度目标" prop="quarter4" min-width="100" align="center">
            <template slot-scope="scope">
              <span v-if="!scope.row.isEdit">{{scope.row.quarter4}}</span>
              <el-input v-if="scope.row.isEdit" v-model="scope.row.quarter4"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="年度目标" prop="yearTotal" min-width="100" align="center"></el-table-column>
          <el-table-column label="操作" min-width="100" align="center">
            <template slot-scope="scope">
              <el-button v-if="!scope.row.isEdit" @click="scope.row.isEdit = true;" type="text" size="small">编辑</el-button>
              <el-button v-if="scope.row.isEdit" @click="saveSale(scope.row)" type="text" size="small">保存</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saleDialog = false">取 消</el-button>
        <el-button type="primary" @click="saleDialog = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import formUtil from '@/utils/formUtil'

  export default {
    data () {
      return {
        itemDialog: false,
        saleDialog: false,
        form: {
          id: '',
          name: '',
          managerId: '',
          managerIdArr: [],
          managerName: '',
          membersId: '',
          membersIdArr: [],
          membersName: ''
        },
        formVerify: {
          name: '请输入团队名称'
        },
        tableData: [],
        kpiRatioArr: [],
        originKpiRatioArr: [],
        typeUrl:['/kpi/preparedKpi', '/kpi/assessKpi', '/kpi/closeKpi'],
        saleData: [],
        saleDate: '2020',
        countryList: [],
        currrentItem: '',
        countryCodeStr: ''
      }
    },
    components:{

    },
    mixins: [dingMixin],
    async mounted(){
      await this.searchItem();
      this.saleDate = (new Date()).getFullYear() + '';
      this.countryList = await this.$httpN.postQ('mpb/market/listCountry', {level: '', query: ''}, false);
      this.countryList.forEach((item) => {
        item.nameCode = item.code + ',' + item.name;
      })
    },
    methods: {
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            return sums[index] = '当前合计目标';
          }else if(index === 1) {
            return sums[index] = this.currrentItem.name;
          }else if(index === 2) {
            return sums[index] = '';
          }

          const values = data.map(item => {
            if(item.type !== 3) return Number(item[column.property])
          });
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
        });

        return sums;
      },
      async saveSale(item) {
        item.year = this.saleDate;
        if(!await this.$httpN.postB('mpb/sale/setGoal', [item], false)) return;
        formUtil.submitSuccess('保存成功');
        this.openSaleDialog(this.currrentItem);
      },
      changeYear() {
        this.openSaleDialog(this.currrentItem);
      },
      openItemDialog(item) {
        if(item) {
          let editData = formUtil.deepCopy(item);
          editData.managerIdArr = editData.managerId.split(',')
          editData.membersIdArr = editData.membersId.split(',')
          let countryCodes = editData.countryCodes ? editData.countryCodes.split(','): [];
          let countryNames = editData.countryNames ? editData.countryNames.split(','): [];
          this.countryCodeStr = [];
          countryCodes.forEach((item, idx) => {
            this.countryCodeStr.push(`${countryCodes[idx]},${countryNames[idx]}`)
          })
          this.form = editData;
        }else{
          this.countryCodeStr = [];
          formUtil.resetData(this.form);
        }
        this.itemDialog = true;
      },
      async openSaleDialog(item) {
        this.saleData = [];
        this.currrentItem = item;
        let membersArr = item.countryCodes.split(',');
        let membersName = item.countryNames.split(',');

        membersArr.forEach((member, idx) => {
          if(member){
            this.saleData.push({
              countryCode: membersArr[idx],
              name: membersName[idx],
              quarter1: '',
              quarter2: '',
              quarter3: '',
              quarter4: '',
              yearTotal: '',
              isEdit: false,
              teamName: item.name
            })
          }
        })

        this.saleDialog = true;
        let data = await this.$httpN.postQ('mpb/sale/listTeamGoal', {teamId: item.id, year: this.saleDate})
        data.forEach(result => {
          this.saleData.forEach((sale) => {
            if(result.countryCode === sale.countryCode) {
              sale.quarter1 = result.quarter1;
              sale.quarter2 = result.quarter2;
              sale.quarter3 = result.quarter3;
              sale.quarter4 = result.quarter4;
              sale.yearTotal = result.yearTotal;
            }
          })
        })
      },
      removeItem(id) {
        formUtil.submitConfirm('此操作将永久删除团队, 是否继续?', async ()=> {
          if(!await this.$httpN.postB('mpb/b2bteam/delete', [id], false)) return;
          formUtil.submitSuccess('删除成功');
          this.searchItem()
        })
      },
      selectDingUsers(ids, name, idsStr, num){
        this.complexPicker(num, [], this.form[ids]).then((data)=>{
          this.form[ids] = data.map(item => item.emplId);
          let names = data.map(item => item.name);
          this.form[name] = names.join(',');
          this.form[idsStr] = this.form[ids].join(',')
        })
      },
      async searchItem() {
        this.tableData = await this.$httpN.postQ('mpb/b2bteam/list')
      },
      async save() {
        if(!formUtil.verifyData(this.form, this.formVerify)) return;
        let countryCodes = [];
        let countryNames = [];
        this.countryCodeStr.forEach((item) => {
          countryCodes.push(item.split(',')[0])
          countryNames.push(item.split(',')[1])
        })
        let postForm = {
          name: this.form.name,
          managerId: this.form.managerId,
          managerName: this.form.managerName,
          membersId: this.form.membersId,
          membersName: this.form.membersName,
          countryCodes: countryCodes.join(','),
          countryNames: countryNames.join(',')
        }
        if(this.form.id) postForm.id = this.form.id
        if(!await this.$httpN.postB('mpb/b2bteam/save', postForm)) return;
        this.itemDialog = false;
        formUtil.submitSuccess('保存成功');
        this.searchItem();
      }
    }
  }
</script>
